import React, { PureComponent, Fragment, Component } from 'react';
import { connect } from 'dva';
import {
	Row,
	Col,
	Card,
	Form,
	Input,
	Radio,
	Select,
	Icon,
	Button,
	Upload,
	message,
	InputNumber,
	Checkbox,
	DatePicker,
	Modal,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './Activity.less';
import { imgPrex } from '../../utils/constData';
import moment from 'moment';
import { routerRedux } from 'dva/router';
import TextArea from 'antd/lib/input/TextArea';
import PeriodOfTime from './PeriodOfTime';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;
const { Option } = Select;
const CheckboxGroup = Checkbox.Group;


const formItemLayout = { labelCol: { span: 4 }, wrapperCol: { span: 15 } };

const priceItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 8 } };
const actItemLayout = { labelCol: { span: 2 }, wrapperCol: { span: 22 } };

const tailFormItemLayout = {
	wrapperCol: {
		xs: { span: 24, offset: 0 },
		sm: { span: 16, offset: 2 },
	},
};
let record, startValue, endValue;

@connect(({ activity, loading, store }) => ({
	activity,
	store,
	storeList: store.storeList.list,
}))
@Form.create()
export default class EditActivity extends PureComponent {
	state = {
		fileList: [],
		file: null,
		image: null,

		showImgUrlList: [],

		priceType1: true,
		priceType2: false,
		editOrAdd: '',

		endOpen: false,
	};

	_setModalVisible(flag, record) {
		console.log(flag);
		if (!flag) {
			this.setState({
				record: null,
				modalVisible: flag,
			});
		} else {
			this.setState({
				record: record,
				modalVisible: flag,
			});
		}
	}

	_handleOk = (fields, form) => {
		const { dispatch } = this.props;
		if (fields.catId) {
			dispatch({
				type: 'category/editCategory',
				payload: fields,
				callback: () => {
					this._setModalVisible(false, null);
					this.handleSearch();
					form.resetFields();
				},
			});
		} else {
			dispatch({
				type: 'category/addCategory',
				payload: fields,
				callback: () => {
					this._setModalVisible(false, null);
					this.handleSearch();
					form.resetFields();
				},
			});
		}
	};

	openModel = () => {
		this.setState({
			modalVisible: true,
		});
	};

	periodOk = arr => {
		const { form } = this.props;
		const str = arr.map(time => time.join('-')).join(',');
		form.setFieldsValue({
			actTimes: str,
		});
		this.setState({
			modalVisible: false,
		});
	};

	periodCancel = () => {
		this.setState({
			modalVisible: false,
		});
	};

	_handleCancel(flag, form) {
		this._setModalVisible(flag);
		form.resetFields();
	}

	componentDidMount() {
		if (this.props.match.params.actId != 'new') {
			this.props.dispatch({
				type: 'activity/fetchActDetail',
				payload: { actId: this.props.match.params.actId },
				callback: data => this._setBackData(data),
			});
			this.setState({
				editOrAdd: this.props.match.params.actId,
			});
		} else {
			this.setState({
				record: null,
			});
		}
		this.props.dispatch({
			type: 'store/fetchStoreList',
			payload: { pageNum: 1, pageSize: 20 },
		});
	}

	_setBackData(data) {
		const { showImagelist } = data;
		const backUrl = showImagelist.map((imglist, i) => {
			return {
				uid: i,
				name: `轮播图${i}`,
				status: 'done',
				url: imglist.showImgUrl,
			};
		});
		this.setState({
			record: data,
			showImgUrlList: backUrl,
			priceType1: data.priceType == '1' || data.priceType == '3',
			priceType2: data.priceType == '2' || data.priceType == '3',
		}, () => {
			this.props.form.setFieldsValue({
				showImgUrlList: backUrl,
			});
		});
	}

	uploadShowImg(option) {
		console.log("option", option);
		this.props.dispatch({
			type: 'activity/addImage',
			payload: option.file,
			callback: data => this._uploadCallback(data),
		});
	}

	showBeforeUpload(file) {
		const isLt1M = file.size / 1024 / 1024 < 1;
		if (!isLt1M) {
			message.error('图片大小不能超过1M');
			return false;
		}
		return true;
	}

	_uploadCallback(data) {
		console.log(data);
		let showImgUrlList = this.state.showImgUrlList.map(item => item);
		let index = 1;
		if (showImgUrlList && showImgUrlList.length > 0) {
			index = showImgUrlList.length + 1;
		}
		let newOne = {};
		newOne['uid'] = index;
		newOne['name'] = '轮播图' + index;
		newOne['status'] = 'done';
		newOne['url'] = imgPrex + data;
		showImgUrlList.push(newOne);
		this.setState({ showImgUrlList });
	}

	_remove(file) {
		console.log(file);
		let newList = this.state.showImgUrlList.filter(item => item.url != file.url);
		this.setState({ showImgUrlList: newList });
	}

	normFile = e => {
		const isLt1M = e.file.size / 1024 / 1024 < 1;
		if (!isLt1M) {
			this.setState({ fileList: [], file: null });
			return this.state.record && this.state.record.actImg ? this.state.record.actImg : null;
		}

		if (e.fileList && e.fileList.length > 0) {
			return e && e.file;
		} else {
			return null;
		}
	};

	showNormFile = e => {
		const isLt1M = e.file.size / 1024 / 1024 < 1;
		if (!isLt1M) {
			return null;
		}
	};

	submit() {
		console.log('this.props.form=====', this.props.form.getFieldsValue());
		this.props.form.validateFields((err, fieldsValue) => {
			if (err) return;

			if (!(this.state.showImgUrlList && this.state.showImgUrlList.length > 0)) {
				message.error('请选择轮播图');
				return;
			}
			console.log('表单提交封面的图片：：：：？？？', this.state.file);
			let showImgUrlList = [];

			if (this.state.showImgUrlList && this.state.showImgUrlList.length > 0) {
				for (let i = 0; i < this.state.showImgUrlList.length; i++) {
					let one = {};
					one['showImgUrl'] = this.state.showImgUrlList[i].url;
					showImgUrlList.push(one);
				}
			}
			if (typeof fieldsValue.actApply === 'string') {
				var values = {
					...fieldsValue,
					name: this.state.file,
					showImgUrlList: showImgUrlList,
					startTime: fieldsValue.startTime.format('YYYY-MM-DD'),
					endTime: fieldsValue.endTime.format('YYYY-MM-DD'),
				};
				console.log('表单提交数据：：：：？？？', values);
			} else {
				var values = {
					...fieldsValue,
					name: this.state.file,
					showImgUrlList: showImgUrlList,
					actApply: fieldsValue.actApply.join(),
					startTime: fieldsValue.startTime.format('YYYY-MM-DD'),
					endTime: fieldsValue.endTime.format('YYYY-MM-DD'),
				};
				console.log('表单提交数据：：：：？？？', values);
			}
			if (values.actId) {
				if(this.state.file == null){
					var values = {
					...fieldsValue,
					//name: this.state.file,
					showImgUrlList: showImgUrlList,
					startTime: fieldsValue.startTime.format('YYYY-MM-DD'),
					endTime: fieldsValue.endTime.format('YYYY-MM-DD'),
					}
				}else{
					var values = {
					...fieldsValue,
					name: this.state.file,
					showImgUrlList: showImgUrlList,
					startTime: fieldsValue.startTime.format('YYYY-MM-DD'),
					endTime: fieldsValue.endTime.format('YYYY-MM-DD'),
					}	
				}
				
				this.props.dispatch({
					type: 'activity/editActivity',
					payload: values,
					callback: (data) => {
					window.sessionStorage.setItem('returnData', JSON.stringify(data));
            this.props.dispatch(routerRedux.push({ pathname: '/activity/appointedday/' + record.actId }))
          },
				});
			} else {
				this.props.dispatch({
					type: 'activity/addActivity',
					payload: values,
					callback: (data) => {
						console.log(data)
						window.sessionStorage.setItem('returnData', JSON.stringify(data));
						this.props.dispatch(routerRedux.push({ pathname: '/activity/appointedday/' + data.actId }))
					},
				});
			}
			
		});
	}

	_callback() {
		this.props.dispatch(routerRedux.goBack());
	}

	changeActApply(e) {
		console.log(e);
	}

	disabledStartDate = startValue => {
		const endValue = this.state.endValue;
		if (!startValue || !endValue) {
			return false;
		}
		return startValue.valueOf() > endValue.valueOf();
	};

	disabledEndDate = endValue => {
		const startValue = this.state.startValue;
		if (!endValue || !startValue) {
			return false;
		}
		return endValue.valueOf() <= startValue.valueOf();
	};

	onChange = (field, value) => {
		this.setState({
			[field]: value,
		});
	};
	onStartChange = value => {
		this.onChange('startValue', value);
	};

	onEndChange = value => {
		this.onChange('endValue', value);
	};

	handleStartOpenChange = open => {
		if (!open) {
			this.setState({ endOpen: true });
		}
	};

	handleEndOpenChange = open => {
		this.setState({ endOpen: open });
	};

	render() {
		const { form, activity, store } = this.props;
		const { editOrAdd, endOpen, modalVisible } = this.state;
		if (editOrAdd != '' || editOrAdd == 'new') {
			record = activity.actDetail;
			let startTime = moment(record.startTime);
			startValue = startTime;
			endValue = startTime;
		} else {
			record = null;
		}

		const uploadProps = {
			onRemove: file => {
				this.setState(({ fileList }) => {
					const index = fileList.indexOf(file);
					const newFileList = fileList.slice();
					newFileList.splice(index, 1);
					return {
						fileList: newFileList,
						file: null,
					};
				});
				this.props.form.setFieldsValue({ name: record && record.actImg ? record.actImg : null });
			},
			beforeUpload: file => {
				const isLt1M = file.size / 1024 / 1024 < 1;
				if (!isLt1M) {
					message.error('图片大小不能超过1M');
					return false;
				}
				this.setState(({ fileList }) => ({
					fileList: [file],
					file: file,
					image: null,
				}));
				this.props.form.setFieldsValue({
					name: file,
				});
				return false;
			},
			fileList: this.state.fileList,
		};

		const showImgUrlListUploadProps = {
			// action: '//jsonplaceholder.typicode.com/posts/',
			onRemove: file => {
				this.setState(({ fileList }) => {
					const index = fileList.indexOf(file);
					const newFileList = fileList.slice();
					newFileList.splice(index, 1);
					return {
						bookletFileList: newFileList,
					};
				});
			},
			beforeUpload: file => {
				this.setState(({ fileList }) => ({
					bookletFileList: [file],
					bookletFile: file,
					bookletImage: null,
				}));

				return false;
			},
			fileList: this.state.bookletFileList,
		};

		return (
			<PageHeaderLayout title="">
				<Card>
					<Form>
						{record ? (
							<FormItem {...formItemLayout} label="id" style={{ display: 'none' }}>
								{form.getFieldDecorator('actId', {
									rules: [{ required: true, message: '请输入id' }],
									initialValue: record ? '' + record.actId : null,
								})(<Input placeholder="请输入id" />)}
							</FormItem>
						) : null}

						<FormItem {...formItemLayout} label="封面">
							{form.getFieldDecorator('name', {
								valuePropName: 'file',
								getValueFromEvent: this.normFile,
								rules: [{ required: true, message: '封面不能为空' }],
								initialValue: record ? record.actImg : null,
							})(
								<Upload {...uploadProps}>
									<Button>
										<Icon type="upload" />浏览
									</Button>
								</Upload>
							)}
							{record && record.actImg && !(this.state.fileList && this.state.fileList.length > 0) ? (
								<img src={imgPrex + record.actImg} style={{ width: 50 }} />
							) : null}
						</FormItem>
						<FormItem {...formItemLayout} label="轮播图">
							{form.getFieldDecorator('showImgUrlList', {
								rules: [{ required: true, message: '请选择轮播图' }],
								initialValue: record ? record.showImgUrlList : null,
							})(
								<Upload
									customRequest={options => this.uploadShowImg(options)}
									listType="picture-card"
									fileList={this.state.showImgUrlList}
									onPreview={this.handlePreview}
									onChange={this.handleChange}
									beforeUpload={file => this.showBeforeUpload(file)}
									onRemove={file => this._remove(file)}
								>
									{this.state.showImgUrlList.length >= 5 ? null : (
										<div>
											<Icon type="plus" />
											<div className="ant-upload-text">上传</div>
										</div>
									)}
								</Upload>
							)}
						</FormItem>

						<FormItem {...formItemLayout} label="名称">
							{form.getFieldDecorator('actName', {
								initialValue: record ? record.actName : null,
								rules: [
									{
										required: true,
										message: '名称不能为空',
									},
								],
							})(
								<Input placeholder="请输入名称，不超过20个字符" style={{ width: '80%' }} maxLength={20} />
							)}
						</FormItem>

						<FormItem {...formItemLayout} label="适用人群：">
							{form.getFieldDecorator('actApply', {
								initialValue: record ? record.actApply : null,
							})(
								<CheckboxGroup onChange={e => this.changeActApply(e)}>
									<Checkbox value={'0'}>普通会员</Checkbox>
									<Checkbox value={'1'}>借阅会员</Checkbox>
									<Checkbox value={'2'}>vip会员</Checkbox>
								</CheckboxGroup>
							)}
						</FormItem>

						<FormItem {...formItemLayout} label="每场人数">
							{form.getFieldDecorator('actUserCount', {
								initialValue: record ? record.actUserCount : null,
								rules: [
									{
										required: true,
										message: '请输入人数',
										pattern: /^[1-9]*[1-9][0-9]*$/ ,
									},
								],
							})(<Input placeholder="请输入人数" style={{ width: '80%' }} maxLength={10} />)}
						</FormItem>

						<FormItem {...formItemLayout} label="最大参加次数">
							{form.getFieldDecorator('actAttendCount', {
								initialValue: record ? record.actAttendCount : null,
								rules: [
									{
										required: true,
										message: '请输入次数',
										pattern: /^[1-9]*[1-9][0-9]*$/,
									},
								],
							})(<Input placeholder="请输入次数" style={{ width: '80%' }} maxLength={10} />)}
						</FormItem>

						<FormItem {...formItemLayout} label="活动门店">
							{form.getFieldDecorator('storeId', {
								rules: [{ required: true, message: '请选择门店' }],
								initialValue: record ? String(record.storeId) : null,
							})(
								<Select style={{ width: '80%' }}>
									<Option value={null}>请选择</Option>
									{this.props.store.storeList.list &&
										this.props.store.storeList.list.length > 0 &&
										this.props.store.storeList.list.map((item, i) => (
											<Option key={i} value={'' + item.storeId}>
												{item.storeName}
											</Option>
										))}
								</Select>
							)}
						</FormItem>
						{/* record */}
						{record ? (
							<Row>
								<Col span={22}>
									<div className={styles.lefttitle}>
										<span>*</span>活动时间：
									</div>
									<div
										className={styles.widthStyle}
										style={{  float: 'left', width: '40%' }}
									>
										<FormItem {...actItemLayout} label="">
											{form.getFieldDecorator('actTimes', {
												initialValue: record ? record.actTimes : null,
												rules: [
													{
														required: true,
														message: '请输入活动时间',
													},
												],
											})(<Input  />)}
										</FormItem>
									</div>
									<div
										className={styles.widthStyle}
										style={{  float: 'left', width: '30%' }}
									>
										<Button type="primary" onClick={this.openModel}>
											编辑时间段
										</Button>
									</div>
								</Col>
							</Row>
						) : (
							<Row>
								<Col span={22}>
									<div className={styles.lefttitle}>
										<span>*</span>活动时间：
									</div>
									<div
										className={styles.widthStyle}
										style={{  float: 'left', width: '41%' }}
									>
										<FormItem {...actItemLayout} label="">
											{form.getFieldDecorator('actTimes', {
												initialValue: "0:00-23:59",
												rules: [
													{
														required: true,
														message: '请输入活动时间',
													},
												],
											})(<Input />)}
										</FormItem>
									</div>
									<div
										className={styles.widthStyle}
										style={{  float: 'left', width: '30%',marginLeft:'3%' }}
									>
										<Button type="primary" onClick={this.openModel}>
											添加时间段
										</Button>
									</div>
								</Col>
							</Row>
						)}

						<Row>
							<Col span={22}>
								<div className={styles.lefttitle}>
									<span>*</span>活动有效期：
								</div>
								<div className={styles.widthStyle} style={{ display: 'flex', float: 'left', width: '30%' }}>
									<FormItem {...actItemLayout} label="">
										{form.getFieldDecorator('startTime', {
											initialValue: record ? moment(record.startTime) : null,
											rules: [
												{
													required: true,
													message: '请输入活动有效期',
												},
											],
										})(
											<DatePicker
												disabledDate={this.disabledStartDate}
												placeholder="开始时间"
												onChange={this.onStartChange}
												value={startValue}
												onOpenChange={this.handleStartOpenChange}
											/>
										)}
									</FormItem>
								</div>
								<div className={styles.widthStyle} style={{ display: 'flex', float: 'left', width: '30%' }}>
									<FormItem {...actItemLayout} label="">
										{form.getFieldDecorator('endTime', {
											initialValue: record ? moment(record.endTime) : null,
											rules: [
												{
													required: true,
													message: '请输入活动有效期',
												},
											],
										})(
											<DatePicker
												disabledDate={this.disabledEndDate}
												placeholder="结束时间"
												onChange={this.onEndChange}
												open={endOpen}
												value={endValue}
												onOpenChange={this.handleEndOpenChange}
											/>
										)}
									</FormItem>
								</div>
							</Col>
						</Row>

						<FormItem {...formItemLayout} label="状态">
							{form.getFieldDecorator('actSts', {
								rules: [{ required: true, message: '请选择商品状态' }],
								initialValue: record ? (record.actSts != 0 ? record.actSts : 1) : 1,
							})(
								<RadioGroup>
									<RadioButton value={1}>上架</RadioButton>
									<RadioButton value={2}>下架</RadioButton>
								</RadioGroup>
							)}
						</FormItem>

						<FormItem {...formItemLayout} label="权重">
							{form.getFieldDecorator('weight', {
								rules: [{ required: true, message: '请输入权重' }],
								initialValue: record ? record.weight : 1000,
							})(
								<InputNumber
									min={0}
									max={999999}
									step={1}
									precision={0}
									placeholder="请输入权重"
									style={{ width: '80%' }}
								/>
							)}
						</FormItem>

						<FormItem {...formItemLayout} label="推荐语">
							{form.getFieldDecorator('recommMsg', {
								rules: [{ required: true, message: '请输入推荐语' }],
								initialValue: record ? record.recommMsg : null,
							})(<Input placeholder="推荐语" style={{ width: '80%' }} />)}
						</FormItem>

						<FormItem {...formItemLayout} label="描述">
							{form.getFieldDecorator('actDes', {
								rules: [{ required: true, message: '请输入描述' }],
								initialValue: record ? record.actDes : null,
							})(<TextArea style={{ width: '80%' }} placeholder="请输入描述" maxLength={1000} />)}
						</FormItem>

						<FormItem {...tailFormItemLayout}>
							<Button
								type="primary"
								htmlType="submit"
								onClick={() => this.submit()}
								loading={this.props.loading}
							>
								下一步
							</Button>
							<Button
								type="danger"
								onClick={() => {
									this.props.dispatch(routerRedux.goBack());
								}}
								style={{ marginLeft: '15px' }}
							>
								取消
							</Button>
						</FormItem>
					</Form>
				</Card>
				<PeriodOfTime
					visible={modalVisible}
					periodOk={this.periodOk}
					periodCancel={this.periodCancel}
					actTimes={record ? record.actTimes : null}
					handleCancel={(flag, form) => this._handleCancel(flag, form)}
				/>
			</PageHeaderLayout>
		);
	}
}
